#include "application.h"
#include "Map.h"
#include <string>

#define HEIGHT 100
#define WIDTH 100

using namespace std;

Application* Application::m_instance = 0;

Application& Application::Instance() {
	if(m_instance==0) {
		m_instance = new Application();
	}
	return *m_instance;
}

Application::Application(void) {
}

void Application::on_key_up(const CL_InputEvent& key, const CL_InputState& state) 
{
	if(key.id == CL_KEY_ESCAPE) 
	{
		quit = true;
	}
}

void Application::on_key_down(const CL_InputEvent& key, const CL_InputState& state)
{
	if(key.id == CL_KEY_LEFT)
	{
		CL_Console::write_line("Left");
		
	}
	if(key.id == CL_KEY_RIGHT)
	{
		CL_Console::write_line("Right");
	}
	if(key.id == CL_KEY_UP)
	{
		CL_Console::write_line("Up");
	}
	if(key.id == CL_KEY_DOWN)
	{
		CL_Console::write_line("Down");
	}
}

void Application::on_mouse_up(const CL_InputEvent &key, const CL_InputState &state) {
    if(key.id == CL_MOUSE_LEFT) {
		CL_Console::write_line("Left Click");
		
    } else if(key.id == CL_MOUSE_RIGHT) {
		CL_Console::write_line("Right Click");
		
	}
}

void Application::on_window_close() {
	quit = true;
}

Application::~Application(void) {
	delete m_instance;
}

void Application::Start() {
	quit = false;
	m_console = new CL_ConsoleWindow("Console");
	CL_SetupCore setup_core;
	CL_SetupDisplay setup_display;
	CL_SetupGL setup_gl;
	
	m_window = new CL_DisplayWindow("", 900, 600,false,true);
	CL_GraphicContext& gc = m_window->get_gc();
	CL_Font font(gc, "Tahoma", 10);
	CL_InputContext ic = m_window->get_ic();
	m_keyboard = new CL_InputDevice(ic.get_keyboard());
	slot_key_up = m_keyboard->sig_key_up().connect(this,&Application::on_key_up);
	slot_quit = m_window->sig_window_close().connect(this, &Application::on_window_close);
	slot_mouse_up = m_window->get_ic().get_mouse().sig_key_up().connect(this,&Application::on_mouse_up);
	slot_key_down = m_keyboard->sig_key_down().connect(this, &Application::on_key_down);

	string inputFileName;
	
	
	unsigned int last_time = CL_System::get_time();
	unsigned int current_time;
	float time_delta_ms;

	Map wood;
	wood.Initialize(HEIGHT, WIDTH);
	wood.ReadInputFile(inputFileName);
	wood.Draw(gc);
	m_window->flip(1);
	while (!quit)
	{
		current_time = CL_System::get_time();
		time_delta_ms = static_cast<float> (current_time - last_time);
		last_time = current_time;
		gc.clear(CL_Colorf(0.0f,0.0f,0.0f));

		wood.NextGeneration();
		wood.CopyCells();
		wood.Draw(gc);

		m_window->flip(1);
		CL_KeepAlive::process(0);
	}

	
}
